package com.qijia.common.service.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.qijia.common.dao.UsersDao;
import com.qijia.common.domain.UserRole;
import com.qijia.common.domain.Users;
import com.qijia.common.service.UserService;

public class UserServiceImpl implements UserService {
	
	private UsersDao userDao = null;
	
	public void setUserDao(UsersDao userDao) {
		this.userDao = userDao;
	}

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {  
        System.out.println("username is " + username);  
        Users users = this.userDao.findByUsername(username);
        if(users == null) {  
            throw new UsernameNotFoundException(username);  
        }  
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);  
          
        boolean enables = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;  
          
        User userdetail = new User(users.getUsername(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);  
        return userdetail;  
    }  
      
    //取得用户的权限  
    private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {  
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
        
        Set<UserRole> roles = user.getUserRole(); 
        for(UserRole userRole : roles) {  
        	System.out.println("用戶角色："+userRole.getRole().getCRoleName());
            authSet.add(new GrantedAuthorityImpl(userRole.getRole().getCRoleName())); 
        }  
        return authSet;  
    }  
}  